import React, { PureComponent } from 'react';
import * as moment from 'moment';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, Modal, Table, DatePicker } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './AdReportList.less';
import AdReportTable from '../../components/AdReportTable';

// const { RangePicker } = DatePicker;
// const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
const formatDate = 'YYYY-MM-DD';
@connect(state => ({
  adReport: state.adReport,
}))
@Form.create()
export default class AdReportList extends PureComponent {
  state = {
    formValues: {},
    modalVisible: false,
    currentName: '',
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'adReport/fetch4Name',
    });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'adReport/fetch4Name',
      payload: {},
    });
  };

  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const { aderName, orderName, adName, startDate, endDate } = fieldsValue;
      const start = startDate ? moment(startDate).format(formatDate) : '';
      const end = endDate ? moment(endDate).format(formatDate) : '';
      dispatch({
        type: 'adReport/fetch4Name',
        payload: {
          aderName: aderName || '',
          orderName: orderName || '',
          adName: adName || '',
          startDate: start,
          endDate: end,
          // endDate: dates[1] || '',
        },
      });
      this.setState({
        formValues: fieldsValue,
      });
    });
  };

  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleShowDetail = (e, payload) => {
    e.preventDefault();
    const { dispatch } = this.props;
    this.setState({
      modalVisible: true,
      currentName: payload.name,
    });
    dispatch({
      type: 'adReport/fetch4Date',
      payload: {
        name: payload.name,
      },
    });
  };
  handleModalOk = () => {
    const downloadDom = document.getElementById('madolExport');
    downloadDom.click();
    this.setState({
      modalVisible: false,
      currentName: '',
    });
  };
  handleExportButtonClick = () => {
    const downloadDom = document.getElementById('export');
    downloadDom.click();
    this.setState({
      modalVisible: false,
      currentName: '',
    });
  };

  renderForm() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <Form.Item label="广告主名称">
              {getFieldDecorator('aderName')(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col md={8} sm={24}>
            <Form.Item label="订单名称">
              {getFieldDecorator('orderName')(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col md={8} sm={24}>
            <Form.Item label="广告名称">
              {getFieldDecorator('adName')(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <Form.Item label="开始日期">
              {getFieldDecorator('startDate')(
                <DatePicker
                  showTime
                  format="YYYY-MM-DD"
                  placeholder="Start"
                />
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <Form.Item label="结束日期">
              {getFieldDecorator('endDate')(
                <DatePicker
                  showTime
                  format="YYYY-MM-DD"
                  placeholder="End"
                />
              )}
            </Form.Item>
          </Col>
          <Col md={3} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
          <Col md={3} sm={24}>
            <a
              id="export"
              href={`http://ad.huolea.com/back_end/adReport/all/byName/excel?aderName=${getFieldValue('aderName') || ''}&orderName=${getFieldValue('orderName') || ''}&adName=${getFieldValue('adName') || ''}`}
              style={{ display: 'none' }}
            >下载
            </a>
            <Button onClick={this.handleExportButtonClick} type="dashed">导出</Button>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { adReport: { loading: adReportLoading, loadingIn, data, data4Date } } = this.props;
    const { formValues, modalVisible, currentName } = this.state;
    return (
      <PageHeaderLayout title="广告数据报表">
        <Card
          bordered={false}
        >
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderForm()}
            </div>
            <AdReportTable
              loading={adReportLoading}
              data={data}
              seachValues={formValues}
              data4Date={data4Date}
              onShowDetail={this.handleShowDetail}
            />
          </div>
        </Card>
        <a
          id="madolExport"
          href={`http://ad.huolea.com/back_end/adReport/all/byDate/excel?name=${currentName}`}
          style={{ display: 'none' }}
        >下载
        </a>
        <Modal
          title="时间明细"
          visible={modalVisible}
          onOk={this.handleModalOk}
          onCancel={() => this.handleModalVisible(false)}
          cancelText="确认"
          okText="导出"
          width={1200}
        >
          <Table
            columns={[
                { title: '日期', dataIndex: 'createAt', render: val => <span>{moment(val).format('YYYY-MM-DD')}</span> },
                { title: '曝光PV', dataIndex: 'exposePV' },
                { title: '曝光UV', dataIndex: 'exposeUV' },
                { title: '点击PV', dataIndex: 'clickPV' },
                { title: '点击UV', dataIndex: 'clickUV' },
                { title: '花费', dataIndex: 'cost', render: (val) => { return val ? val.toFixed(2) : 0; } },
                { title: 'CTR(%)', dataIndex: 'ctr', render: (val) => { return val ? val.toFixed(2) * 100 : 0; } },
                { title: 'CPM', dataIndex: 'cpm', render: (val) => { return val ? val.toFixed(2) : 0; } },
                { title: 'CPC', dataIndex: 'cpc', render: (val) => { return val ? val.toFixed(2) : 0; } },
               ]}
            loading={loadingIn}
            pagination={false}
            // pagination={{
            //   total: payment.totalElements,
            //   pageSize: payment.size,
            //   current: parseInt(payment.number, 10) + 1 || 1,
            // }}
            dataSource={data4Date.content}
          />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
